/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name : 'step',
			title : 'step',
			type : 'LineEdit',
			property : {tool_tip : '目标step,默认是orig'},
		},
		{
			name : 'outline',
			title : 'outline',
			type : 'LineEdit',
			property : {tool_tip : '目标outline,默认是ol'},
		},
		{
			name : 'units',
			title : '单位',
			type : 'RadioBox',
			property : {
				size_policy:'Expanding,Fixed',
				item_list:[
					{name:'inch',text:'INCH'},
					{name:'mm',text:'MM'},
				],
				tool_tip:'工作单位，未设定，默认为INCH'
			},
			pack : {row:1,column:1},
		},
		{
			name : 'tmp_enlarge_ss',
			title : '文字临时涨大辅助',
			type : 'LineEdit',
			property : {tool_tip : ''},
		},
		{
			name : 'cover_layer_suffix',
			title : '文字套层后缀',
			type : 'LineEdit',
			property : {tool_tip : ''},
		},
		{
			name : 'silk_suffix',
			title : '分离的文字层后缀',
			type : 'LineEdit',
			property : {tool_tip : ''},
		},
		{
			name : 'text_height',
			title : '文字最大高度',
			type : 'LineEdit',
			property : {tool_tip : ''},
		},
		{
			name : 'ss_elarge_height',
			title : '文字放大高度',
			type : 'LineEdit',
			property : {tool_tip : ''},
		},
		{
			name : 'bk_suffix',
			title : '备份层后缀',
			type : 'LineEdit',
			property : {tool_tip : ''},
		},
		{
			name : 'select_lyr',
			title : '选择层别',
			type : 'RadioBox',
			property : {
				size_policy:'Expanding,Fixed',
				item_list:[
					{name:'yes',text:'Yes'},
					{name:'no',text:'No'},
				],
				tool_tip:'未设定，默认为Yes'
			},
			pack : {row:1,column:1},
		},
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.00 2020-09-01 Scott Sun
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 标题 </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> step信息 </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("=============================:template");
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
require("topsin.genmath")
var genMath = new GenMath();
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db
var PAR = {}
if ($.par) { PAR = $.par } else if ($.hasOwnProperty('script_parameter')){ PAR = JSON.parse($.script_parameter); }
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({ table: "pdm_aimdfm_task", data: { current_process_title: $.process_title }, where: { id: $.task_id } });
	}
}
var Status = 'ok';
var resultData = [];
var par = PAR;
var default_par = {
	units:"mm",
	ss_to_sm: 10,		// 文字距离阻焊
	ss_to_smd: 10,		// 文字距离SMD
	ss_to_bga: 10,		// 文字距离bga
	text_height: 1,   // 文字最大高度
	bk_suffix: "_bk",  // 备份层后缀
	silk_suffix: "_font", // 分离的文字层后缀
	cover_layer_suffix: "_cover_tmp",
	tol: 1,
	select_lyr: "no",
	step: "unit",
	ss_elarge_height:2000,
	tmp_enlarge_ss:700,
	auto_save: "No",
	outline: "ol"
}
for(var key in default_par){ if (!par.hasOwnProperty(key) || par[key] == ""){ par[key] = default_par[key] }}
var job = Job;
var outline = par.outline
var gui = new NewGUI(GUI);
if(!par.outline_size){
    par.outline_size  =  par.units == 'inch' ? 7.87 : 200;
}
try {
	if(_.isEmpty(job)){throw "参数job不存在"} else { job = job.toLowerCase() }
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
    if(mode == "aimdfm"){ if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" } else { GEN.checkInout({job:job,mode:"out"}) } }

	var workstep = getWorkStep()
	if(!Array.isArray(workstep)){throw "工作step错误"}

	var err = slOptimize({workstep:workstep}) // 文字优化
	if (err) {throw err}

	// 保存 
	if(/yes/ig.test(par.auto_save)){GEN.checkInout({job:job,mode:"out"}); GEN.saveJob({ job: job });GEN.checkInout({job:job,mode:"in"});GEN.closeJob({job:job});} else {GEN.checkInout({job:job,mode:"in"})}
	if (mode === "aimdfm") {
		$.QDfm.updateRow({table: "pdm_aimdfm_task",data: {progress: 33.33},where: { id: $.task_id }});
		if (GEN.hasError()) { Status = 'error';resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {status: Status,result_data: resultData};
		} else { resultData.push({ type: "info", title: "操作完成, 请注意检查!" }); return {status: Status,result_data: resultData}; }
	}else { return "Done" }
} catch (e) {
	IKM.msg(_.join(GEN.STATUS, "\n"));IKM.msg(e);Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
    return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}

// 文字放大
function slOptimize(props) {
	// var info = gui.showForm({
	// 	title : '请手动匹配以下信息',
	// 	showcheck : 1,gen:GEN,
	// 	defaultsize:[200,100],
	// 	ui: {
	// 		type: 'ScrollArea',
	// 		property: { widget_resizable: true, frame_shape: 'NoFrame', align: 'Top' },
	// 		child: {
	// 			type: 'VBoxLayout',
	// 			property: { margin: 2, spacing: 5, align: 'Top' },
	// 			pack: { stretch: 0 },
	// 			child:[{
	// 				type: "FormGridLayout",
    //                 property: { columns: 1, label_alignment: 'Top | Right', margin: 10, spacing: 20 },
    //                 pack: { stretch: 0 },
	// 				child:[{
	// 					name : 'font_symbol',
	// 					pack: { label: '文字symbol' },
	// 					type : 'LineEdit',
	// 					setter: function(obj){ obj.setText() },
	// 					units: 'um',
	// 					property: { enabled: true, value:200 }
	// 				},
	// 				{
	// 					name : 'tmp_enlarge_ss',
	// 					pack: { label: '文字作为辅助临时扩大' },
	// 					type : 'LineEdit',
	// 					units: 'um',
	// 					setter: function(obj){ obj.setText() },
	// 					property: { value:par.tmp_enlarge_ss,enabled: true }
	// 				},
	// 				{
	// 					name : 'font_height',
	// 					pack: { label: '字高(um)' },
	// 					type : 'LineEdit',
	// 					units: 'um',
	// 					setter: function(obj){ obj.setText() },
	// 					property: { value:par.ss_elarge_height,enabled: true }
	// 				},
	// 				{
	// 					type: "stretch"
	// 				}]
	// 			}]
	// 		}
	// 	}
	// });
	// if(!info){throw "未填写参数"}
	// info = JSON.parse(JSON.stringify(info))
	info = {
		font_height: 1500,
		font_symbol: 200,
		tmp_enlarge_ss: 500
	}
	var font_height = info.font_height;
	var font_symbol = info.font_symbol;
	var tmp_enlarge_ss = info.tmp_enlarge_ss;
	// 1. step过滤
	var workstep = props.workstep;
	// 2.过滤工作层
	var work_layers = getLayer({layer_type:"silk_screen", context: "board"})
	if(/yes/ig.test(par.select_lyr)){
		var matrix = GEN.getMatrix({job:job});
		var layers = Object.keys(matrix).map(function(key){
			var tmp  ={};
			tmp[key] = key;
			return tmp
		})
		work_layers = gui.selectMultiple({defaultsize:[200,100],title: "请先择工作层",list: layers,defaultvalue: work_layers,columns: 4,gen: GEN})	
	}
	if(work_layers.length == 0 ) {return "没有先择layer"}

	var matrix = GEN.getMatrix({job:job})

	workstep.forEach(function(step) {
		GEN.openStep({job:job, name:step})
		GEN.units({type:par.units})
		GEN.COM( "sel_options,clear_mode=clear_after,display_mode=all_layers,area_inout=inside,area_select=select,select_mode=standard,area_touching_mode=exclude");
		GEN.zoomHome();
		work_layers.forEach(function(layer){
			var font_layer = layer + par.silk_suffix;
			GEN.workLayer({name:font_layer,display_number:2,clear_before:'yes'})
			GEN.selChangeSym({symbol:"r" + font_symbol})
			var tmp1 = font_layer + "_1";
			var tmp2 = font_layer + "_2";
			var tmp3 = font_layer + "_3";
			var bk = font_layer + "_bk";
			var bk2 = font_layer + "_ok";
			var bk_tmp = font_layer + "_ok_tmp";
			var bk_ok2 = font_layer + "_ok2";
			
			[tmp1,tmp2,tmp3,bk,bk2,bk_tmp,bk_ok2].forEach(function(v){
				if(GEN.isLayerExists({job:job, layer:v})){GEN.deleteLayer({job:job,layer:[v]})}
			})
			// GEN.copyLayer({source_job:job,source_step:step,source_layer:font_layer,dest_layer:tmp1, mode:"replace"})
			GEN.copyLayer({source_job:job,source_step:step,source_layer:font_layer,dest_layer:tmp3, mode:"replace"})
			GEN.copyLayer({source_job:job,source_step:step,source_layer:font_layer,dest_layer:bk2, mode:"replace"})
		
			// GEN.copyLayer({source_job:job,source_step:step,source_layer:font_layer,dest_layer:bk, mode:"replace"})
			GEN.affectedLayer({affected:'no',mode:'all'})
			GEN.selClearFeature()
			// GEN.workLayer({name:tmp1,display_number:2,clear_before:'yes'})
			// GEN.selChangeSym({symbol:"r0.1"})

			// 利用tmp3 快速定位
			GEN.workLayer({name:tmp3,display_number:2,clear_before:'yes'})
			GEN.units({type:"mm"})
			GEN.selChangeSym({symbol:"r" + tmp_enlarge_ss})
			// 转铜皮  获取每一个铜皮的limits信息
			GEN.selContourize()
			var fast_features = GEN.getFeatures({job:job,step:step,layer:tmp3,options:"feat_index",surface:1,units:"mm"})
			fast_features = featsToLimits(fast_features)
			fast_features.forEach(function(item){
				if(item.limit.xsize > item.limit.ysize) {
					var k = font_height / (item.limit.ysize * 1000)
					item.x_scale = k
					item.y_scale = k
				} else {
					var k = font_height / (item.limit.xsize * 1000)
					item.y_scale = k
					item.x_scale = k
				}
			})
			fast_features.forEach(function(item){
				GEN.workLayer({name:bk2,display_number:2,clear_before:'yes'})
				GEN.COM("filter_area_strt")
				GEN.COM("filter_area_xy,x="+item.limit.xmin+",y=" + item.limit.ymin)
				GEN.COM("filter_area_xy,x="+item.limit.xmax+",y=" + item.limit.ymax)
				GEN.COM("filter_area_end,layer=,filter_name=popup,operation=select,area_type=rectangle,inside_area=yes,intersect_area=yes")
				if(GEN.getSelectCount() > 0 ) {
					GEN.selMoveOther({target_layer:bk_tmp,invert:'no',dx:0,dy:0,size:0})
					GEN.workLayer({name:bk_tmp,display_number:2,clear_before:'yes'})
					var tmp_limitbk = GEN.getLayerLimits({job:job,step:step,layer:bk_tmp,units:'mm'})
					tmp_limitbk.xc = Number(tmp_limitbk.xmin) + tmp_limitbk.xsize/2
					tmp_limitbk.yc = Number(tmp_limitbk.ymin) + tmp_limitbk.ysize/2
					tmp_limitbk.xsize = Number(tmp_limitbk.xsize)
					tmp_limitbk.ysize = Number(tmp_limitbk.ysize)
					var k;
					var sym = 0;
					var syms = GEN.getLayerSymsHist({job:job,step:step,layer:bk_tmp,options:'break_sr',units:'mm'})
					for (var key in syms) {
						var symInfo = syms[key];
						if(symInfo.size){
							var size = symInfo.size;
							if(sym == 0){
								sym = size
							} else {
								sym = size > sym? sym : size
							}			
						}
					}
					if(tmp_limitbk.xsize > tmp_limitbk.ysize) {
						k = (font_height-sym) / (tmp_limitbk.ysize * 1000 - sym)
					} else {
						k = (font_height-sym) / (tmp_limitbk.xsize * 1000 - sym)
					}
					if(k > 0 && k < 10) {
						GEN.selTransform({mode:'anchor',oper:'scale',x_anchor: tmp_limitbk.xc,y_anchor: tmp_limitbk.yc,x_scale:k,y_scale:k})
					}
					GEN.selMoveOther({target_layer:bk_ok2,invert:'no',dx:0,dy:0,size:0})
				}
			})
			// 框选
			var flag = true;
			IKM.msg(font_layer + "层：请选择需放大的文字，不需制作了请【左键框选空白处】")
			var x_or_y = "x";
			while(flag){
				var bk2_tmp = bk2 + "_tmp"
				GEN.workLayer({name:bk_ok2,display_number:1,clear_before:'yes'});
				GEN.displayLayer({name:bk2, number:2});
				GEN.displayLayer({name:font_layer, number:3});
				
				var tmp_con = GEN.MOUSE({type:'r',text:"Please Select"});

				GEN.workLayer({name:font_layer,display_number:1,clear_before:'yes'});
				GEN.COM("filter_area_strt")
				GEN.COM("filter_area_xy,x="+tmp_con.x1+",y="+tmp_con.y1)
				GEN.COM("filter_area_xy,x="+tmp_con.x2+",y="+tmp_con.y2)
				GEN.COM("filter_area_end,layer=,filter_name=popup,operation=select,area_type=rectangle,inside_area=yes,intersect_area=no")
				if(GEN.getSelectCount() > 0){
					var info2 = gui.showForm({
						title : '请手动匹配以下信息',
						showcheck : 1,gen:GEN,
						defaultsize:[200,100],
						ui: {
							type: 'ScrollArea',
							property: { widget_resizable: true, frame_shape: 'NoFrame', align: 'Top' },
							child: {
								type: 'VBoxLayout',
								property: { margin: 2, spacing: 5, align: 'Top' },
								pack: { stretch: 0 },
								child:[{
									type: "FormGridLayout",
									property: { columns: 1, label_alignment: 'Top | Right', margin: 10, spacing: 20 },
									pack: { stretch: 0 },
									child:[{
										name : 'font_symbol',
										pack: { label: '文字symbol' },
										type : 'LineEdit',
										setter: function(obj){ obj.setText() },
										units: 'um',
										property: { enabled: true, value:"200" }
									},
									{
										name : 'x_or_y',
										pack: { label: '文字方向' },
										type : 'LineEdit',
										setter: function(obj){ obj.setText() },
										property: { value:x_or_y,enabled: true }
									},
									{
										name: 'font_height',
										pack: { label: '字高(um)' },
										type: 'LineEdit',
										units: 'um',
										setter: function (obj) { obj.setText() },
										property: {value: par.ss_elarge_height,enabled: true }
									},
									{
										type: "stretch"
									}]
								}]
							}
						}
					});
					if(!info2){throw "未填写参数"}
					info2 = JSON.parse(JSON.stringify(info2))
					x_or_y = info2.x_or_y;
					var font_height2 = info2.font_height;
					var tmp_layer = font_layer + "_tmp";
					selCopyOther({delExist:true,layer: tmp_layer})
					GEN.workLayer({name:tmp_layer,display_number:1,clear_before:'yes'});
					GEN.selAllFeat()
					selCopyOther({delExist:true,layer: bk2_tmp})
					GEN.workLayer({name:bk2,display_number:1,clear_before:'yes'});
					GEN.COM("filter_area_strt")
					GEN.COM("filter_area_xy,x="+tmp_con.x1+",y="+tmp_con.y1)
					GEN.COM("filter_area_xy,x="+tmp_con.x2+",y="+tmp_con.y2)
					GEN.COM("filter_area_end,layer=,filter_name=popup,operation=select,area_type=rectangle,inside_area=yes,intersect_area=no")
					if(GEN.getSelectCount() > 0) {GEN.selDelete()}
					GEN.workLayer({name:tmp_layer,display_number:1,clear_before:'yes'});
					var limits = GEN.getLayerLimits({job:job,step:step,layer:tmp_layer, units:"mm"})
					for (var key in limits) {
						limits[key] = limits[key] - 0;
					}
					limits.xc = Number(limits.xmin) + limits.xsize/2
					limits.yc = Number(limits.ymin) + limits.ysize/2

					var sym = 0;
					var syms = GEN.getLayerSymsHist({job:job,step:step,layer:tmp_layer,units:'mm'})
					for (var key in syms) {
						var symInfo = syms[key];
						if(symInfo.size){
							var size = symInfo.size;
							if(sym == 0){
								sym = size
							} else {
								sym = size > sym? sym : size
							}			
						}
					}
					// 获取里面有几个字母 每一个字母的limits信息
					GEN.selChangeSym({symbol:"r1"})
					GEN.selContourize()
					var feas = GEN.getFeatures({job:job,step:step,layer:tmp_layer,options:"feat_index",units:"mm"})
					// if(feas.length == 1) {
						GEN.workLayer({name:bk2_tmp,display_number:2,clear_before:'yes'});
						var k = (font_height2-sym) / ((x_or_y=="y"? limits.xsize : limits.ysize)* 1000 - sym)
						GEN.selTransform({mode:'anchor',oper:'scale',x_anchor:limits.xc,y_anchor:limits.yc,x_scale:k,y_scale:k}) 
						GEN.selMoveOther({target_layer:bk2,invert:'no',dx:0,dy:0,size:0}) 
					// } else if (feas.length > 1) {
					// 	var limits_info = [];
					// 	feas.forEach(function(item) {
					// 		var index = item.index;
					// 		GEN.selLayerFeat({layer:tmp_layer, index:index,operation:"select"});
					// 		if(GEN.getSelectCount() > 0) {
					// 			var tmp_l = GEN.getLayerLimits({job:job,step:step,layer:tmp_layer, units:"mm", options:"select"})
					// 			for (var key in tmp_l) {
					// 				tmp_l[key] = tmp_l[key] - 0;
					// 			}
					// 			tmp_l.xc = Number(tmp_l.xmin) + tmp_l.xsize/2
					// 			tmp_l.yc = Number(tmp_l.ymin) + tmp_l.ysize/2
					// 			limits_info.push({index:index, limits:tmp_l })
					// 			GEN.selClearFeature()
					// 		}
					// 	})
					// 	var rodata = []
					// 	limits_info.forEach(function (item, i) {
					// 		if(limits_info[i+1]){
					// 			rodata.push(getRodate({
					// 				xs : item.limits.xc,
					// 				ys : item.limits.yc,
					// 				xe : limits_info[i+1].limits.xc,
					// 				ye : limits_info[i+1].limits.yc
					// 			}))
					// 		}
					// 	})
					// 	var angle = rodata.reduce(function(a,b) {return a + b}) / rodata.length;
					// 	if (Math.abs(angle) < 10) { angle = 0 }
					// 	GEN.workLayer({name:bk2_tmp,display_number:2,clear_before:'yes'});
					// 	GEN.selTransform({mode:'anchor',oper:"rotate",x_anchor:limits.xc,y_anchor:limits.yc,angle:angle})
					// 	// 按照中心放大
					// 	var limits2 = GEN.getLayerLimits({job:job,step:step,layer:tmp_layer, units:"mm"})
					// 	for (var key in limits) {
					// 		limits2[key] = limits2[key] - 0;
					// 	}
					// 	limits2.xc = limits2.xmin + limits2.xsize/2
					// 	limits2.yc = limits2.ymin + limits2.ysize/2
					// 	if(limits2.xsize > limits2.ysize) {
					// 		var k = (font_height2 - sym) / ((x_or_y=="y"? limits2.xsize : limits2.ysize)* 1000 - sym)
					// 		limits2.x_scale = k
					// 		limits2.y_scale = k
					// 	} else {
					// 		var k = (font_height2 - sym) / ((x_or_y=="y"? limits2.xsize : limits2.ysize)* 1000 - sym)
					// 		limits2.y_scale = k
					// 		limits2.x_scale = k
					// 	}
					// 	GEN.selTransform({mode:'anchor',oper:'scale',x_anchor:limits2.xc,y_anchor:limits2.yc,x_scale:limits2.x_scale,y_scale:limits2.y_scale}) 
					// 	GEN.selTransform({mode:'anchor',oper:"rotate",x_anchor:limits.xc,y_anchor:limits.yc,angle:360 - angle})
					// 	GEN.selMoveOther({target_layer:bk2,invert:'no',dx:0,dy:0,size:0}) 
					// }
					GEN.deleteLayer({job:job, layer:[tmp_layer]})
				} else {
					flag = false
				}
				if(GEN.isLayerExists({job:job, layer:bk2_tmp})) {
					GEN.deleteLayer({job:job, layer:[bk2_tmp]})
				}
			}
			GEN.PAUSE("check")
			// 将ok的移动到文字层
			GEN.clearLayers()
			GEN.workLayer({name:font_layer,display_number:2,clear_before:'yes'});
			GEN.selDelete();
			GEN.clearLayers()
			GEN.affectedLayer({affected:"yes", layer:[bk2, bk_ok2]})
			GEN.selMoveOther({target_layer:layer,invert:'no',dx:0,dy:0,size:0});
			[tmp1,tmp2,tmp3,bk,bk2,font_layer,bk_ok2, layer+cover_layer_suffix].forEach(function(v){
				if(GEN.isLayerExists({job:job, layer:v})){GEN.deleteLayer({job:job,layer:[v]})}
			})
		})
	})
}	

function selCopyOther(props){ // {layer , invent,  dx, dy , size}
    if(GEN.getSelectCount()>0){ if(!props || !props.layer){return}
        if(props.delExist){if(GEN.isLayerExists({job:job, layer:props.layer})){GEN.deleteLayer({job:job, layer:[props.layer]})}}
        GEN.selCopyOther({dest:'layer_name',target_layer:props.layer,invert:props.invert || 'no',dx:props.dx || 0,dy:props.dy || 0,size:props.size || 0})
    }
}

function getLayer(props){
    if(!props){return}
    if(!props.context){props.context = "board"}
    var matrix = GEN.getMatrix({job:job})
    return Object.keys(matrix).reduce(function(a,b){
        var info = matrix[b];
        var ret = true;
        for (var key in props) { if(!Array.isArray(props[key])){props[key] = [props[key]]}
        if(info[key] && props[key].indexOf(info[key]) < 0){ ret = false } }
        if(ret){  a.push(props.res == "info"? info : b) } return a
    },[])
}

function NewGUI (gui) {
    this.msgBox = function(props){ // title  type  content  button
        props = props || {}
        return gui.msgBox(props.title || "title",props.type || "info",props.content || "content",props.button || ["ok", "cancel"]);
    }
    this.selectFromTreeview = gui.selectFromTreeview
    this.confirm = function(props) {
        props = props || {}
        return gui.confirm(props.content || "content",props.button || ["yes", "no"], props.type || "question");
    }
    this.selectFile = function(props){ // "choose something", "*", true, "file", "/home/abby/fast_io"
        props = props || {}
        return gui.selectFile(props.title || "choose something",props.filter || "*",props.multiple || false, "file","");
    }
    this.selectSingle = function(props) {
        props = props || {}
        return gui.selectSingle({
            "title": props.title || "select",
            "list": props.list || [],
            "default": props["default"] || "",
            "columns": props.columns || 2,
            "gen":props.gen || GEN
        });
    }
    this.selectMultiple = function(props) {
        props = props || {}
        return gui.selectMultiple({
            "title": props.title || "select",
            "list": props.list || [],
            "defaultvalue": props["defaultvalue"] || [""],
            "defaultsize": props["defaultsize"] || [200, 100],
            "columns": props.columns || 2,
            "gen":props.gen || GEN
        });
    }
    this.selectFromTable = gui.selectFromTable
    this.snapScreen = gui.snapScreen
    this.imageViewer = gui.imageViewer
    this.inputBox = gui.inputBox
    this.showForm = gui.showForm
    this.selectLayer = function(props){
        props = props || {}
        return gui.selectLayer({
            title: props.title || "请选择层",
            filter: props.filter || ".*", // regular expression
            selectmode: props.selectmode || "multiple", // single, multiple
            context: props.context || "all", // all, board, misc
            layertype: props.layertype || "signal", // default type of layertypelist
            defaultsize: props.defaultsize || [600, 400], // window size
            layermatrix: props.layermatrix || props.matrix,
            layertypelist: props.layertypelist || [
                {name: "all", display_name: "all", filter: function(x) { return x }},
                {name: "signal", display_name: "signal", filter: function(x) { return x["layer_type"] === "signal"; }},
                {name: "power_ground", display_name: "power_ground", filter: function(x) { return x["layer_type"] === "power_ground"; }},
                {name: "mixed", display_name: "mixed", filter: function(x) { return x["layer_type"] === "mixed"; }},
                {name: "solder_mask", display_name: "solder_mask", filter: function(x) { return x["layer_type"] === "solder_mask"; }},
                {name: "silk_screen", display_name: "silk_screen", filter: function(x) { return x["layer_type"] === "silk_screen"; }},
                {name: "solder_paste", display_name: "solder_paste", filter: function(x) { return x["layer_type"] === "solder_paste"; }},
                {name: "drill", display_name: "drill", filter: function(x) { return x["layer_type"] === "drill"; }},
                {name: "rout", display_name: "rout", filter: function(x) { return x["layer_type"] === "rout"; }},
                {name: "document", display_name: "document", filter: function(x) { return x["layer_type"] === "document"; }}
            ],
            gen: props.GEN || GEN
        })
    } 
    this.lockUnlockLayer = function(props){
        props = props || {}
        var tmp = {}
        if (props.matrix) {
            for (var key in props.matrix) {
                var item = props.matrix[key]
                tmp[key] = {
                    row : item.row,
                    name : item.name
                }
            }
        }
        return gui.lockUnlockLayer({
            title: props.title || "lockUnlockLayer",
            layermatrix:props.layermatrix || tmp 
        })
    } 
    this.passwordBox = function(props){
        props = props || {}
        return gui.passwordBox({title:props.title || "password", password:props.password || "1212"})
    } 
    this.selectJobLayer = function (props) {
        props = props || {}
        return gui.selectJobLayer({
            layertypelist: props.layertypelist || [
                {name: "all", display_name: "all", filter: function(x) { return x }},
                {name: "signal", display_name: "signal", filter: function(x) { return x["layer_type"] === "signal"; }},
                {name: "power_ground", display_name: "power_ground", filter: function(x) { return x["layer_type"] === "power_ground"; }},
                {name: "mixed", display_name: "mixed", filter: function(x) { return x["layer_type"] === "mixed"; }},
                {name: "solder_mask", display_name: "solder_mask", filter: function(x) { return x["layer_type"] === "solder_mask"; }},
                {name: "silk_screen", display_name: "silk_screen", filter: function(x) { return x["layer_type"] === "silk_screen"; }},
                {name: "solder_paste", display_name: "solder_paste", filter: function(x) { return x["layer_type"] === "solder_paste"; }},
                {name: "drill", display_name: "drill", filter: function(x) { return x["layer_type"] === "drill"; }},
                {name: "rout", display_name: "rout", filter: function(x) { return x["layer_type"] === "rout"; }},
                {name: "document", display_name: "document", filter: function(x) { return x["layer_type"] === "document"; }}
            ],
            //defaultlayertype: "ha",
            joblist: props.joblist || [],
            defaultJob: props.defaultJob || [], // select by default
            steplist: props.steplist || [],
            // defaultstep: "step3",
            showstep: props.showstep || true,
            selectmode: props.selectmode || "multiple", // single/multiple
            layermatrix: props.layermatrix || {  },
            defaultlayer: props.defaultlayer || []
        })
    }
}

function getWorkStep(props){
	var steplists = GEN.getStepList({job:job});
	if(steplists.length == 0){return "该料号没有step"}
	steplists = steplists.filter(function(name){
		var reg = new RegExp(par.step, "ig")
		return reg.test(name)
	})
	if(steplists.length == 0){return "根据脚本参数过滤出来的step不存在，请检查资料或者脚本参数配置！"}
	return steplists
}


function delLayer(layer){
	if(!Array.isArray(layer)){
		layer = [layer]
	}
	layer = layer.filter(function(v){return GEN.isLayerExists({job:job, layer:v})})
	if(layer.length){
		GEN.deleteLayer({job:job, layer:layer})
	}
}

function correct(work_layer){
	var tmp = GEN.getWorkLayer();
	return tmp !== work_layer;
}

function getAngle(features){ // 获取最长边的角度
	features.sort(function(a,b){
		a.length = getLineLength(a);
		b.length = getLineLength(b);
		return a.length - b.length
	})
	return getRodate(features[features.length - 1])
}
function getLineLength (line){
    if (line.type != "line"){return 0}
    return Math.sqrt((line.xe - line.xs)*(line.xe - line.xs) + (line.ye - line.ys)*(line.ye - line.ys)) 
}
function getRodate(props){
    var xs = props.xs;
    var ys = props.ys;
    var xe = props.xe;
    var ye = props.ye;
    var y = ye - ys;
    var x = xe - xs;
    var r = Math.atan(y / x)
    return r*180/Math.PI
}

function sameDirection(xory, type, res, indexes) {
	for (var key in xory) {
		var current = -1;
		var data = xory[key];
		data.sort(function(a,b){return a[type] - b[type]})
		data.forEach(function(item, i){
			if (i > current){
				var ret = [item];
				current = searchFont(item, data, i, ret,type)
				if(ret.length > 1) {
					ret.forEach(function(item) {
						indexes = indexes.filter(function(item2){
							return item2.index != item.index
						})
					})
					
					res.push(ret.reduce(function(a,b){
						if(Number(b.limit.xmin) < Number(a.xmin)){
							a.xmin = b.limit.xmin
						}
						if(Number(b.limit.ymin) < Number(a.ymin)){
							a.ymin = b.limit.ymin
						}
						if(Number(b.limit.xmax) > Number(a.xmax)){
							a.xmax = b.limit.xmax
						}
						if(Number(b.limit.ymax) > Number(a.ymax)){
							a.ymax = b.limit.ymax
						}
						return a
					},{
						xmin: item.limit.xmin,
						ymin: item.limit.ymin,
						xmax: item.limit.xmax,
						ymax: item.limit.ymax
					}))
				}
			}
		})
	}
	return indexes
}
function searchFont(l ,arr, i, ret, type){
	if(arr[i+1]){
		var len =  Math.abs(l[type] - arr[i+1][type])
		if(len <= 1.5){
			ret.push(arr[i+1])
			return searchFont(arr[i+1], arr, i+1, ret, type)
		} else {return i}
	}
	return i+1
}
function turnFix(data) {
	return parseFloat(data).toFixed(1)
}
function surfaceAnalysis(props){
	props.limit.xmin = props.limit.xmin - 0; 
	props.limit.ymin = props.limit.ymin - 0; 
	props.limit.xmax = props.limit.xmax - 0; 
	props.limit.ymax = props.limit.ymax - 0; 
	props.limit.xsize = props.limit.xsize - 0; 
	props.limit.ysize = props.limit.ysize - 0; 
	props.xc = props.limit.xsize / 2 + props.limit.xmin
	props.yc = props.limit.ysize / 2 + props.limit.ymin
}

// function featsToLimits(feats) {
//     feats.forEach(function(item) {
//         if(item.feats) {
//             var polygon = genMath.profile2Polygon(item.feats.join("\n"),0)
//             var res = polygon.reduce(function(a,b){
//                 a.xmin = b.x > a.xmin ? a.xmin : b.x;
//                 a.ymin = b.y > a.ymin ? a.ymin : b.y;
//                 a.xmax = b.x < a.xmax ? a.xmax : b.x;
//                 a.ymax = b.y < a.ymax ? a.ymax : b.y;
//                 return a
//             }, {
//                 xmin: polygon[0].x,
//                 ymin: polygon[0].y,
//                 xmax: polygon[0].x,
//                 ymax: polygon[0].y
//             })
//             res.xsize = Math.abs(res.xmax - res.xmin) 
//             res.ysize = Math.abs(res.ymax - res.ymin) 
//             res.xc = res.xmin + res.xsize/2
// 			res.yc = res.ymin + res.ysize/2
//             item.limits = res
//             item.limit = res
//         }
//     })
//     return feats
// }


function featsToLimits(feats) {
    feats.forEach(function(item) {
        if(item.feats) {
			var polygon = profile2Polygon(item.feats)
            var res = polygon.reduce(function(a,b){
                a.xmin = b.x > a.xmin ? a.xmin : b.x;
                a.ymin = b.y > a.ymin ? a.ymin : b.y;
                a.xmax = b.x < a.xmax ? a.xmax : b.x;
                a.ymax = b.y < a.ymax ? a.ymax : b.y;
                return a
            }, {
                xmin: polygon[0].x,
                ymin: polygon[0].y,
                xmax: polygon[0].x,
                ymax: polygon[0].y
            })
            res.xsize = Math.abs(res.xmax - res.xmin) 
            res.ysize = Math.abs(res.ymax - res.ymin) 
            res.xc = res.xmin + res.xsize/2
			res.yc = res.ymin + res.ysize/2
            item.limits = res
            item.limit = res
        }
    })
    return feats
}

function profile2Polygon(feat) {
	var info = [];
	feat.forEach(function(v){
		if (/^#O. ([\S]+) ([\S]+)/.test(v)) {
			info.push({
				x: RegExp.$1 - 0,
				y: RegExp.$2 - 0
			})
		}
	})
	return info
}